package com.lcc.myblog.controller;

import com.lcc.lynx.base.system.util.FTPUtil;
import com.lcc.lynx.security.annotation.Anonymous;
import com.lcc.myblog.common.result.ImgResultVO;
import com.lcc.myblog.service.BkWorkBillService;
import com.lcc.myblog.pojo.dv.BkWorkBillDV;
import com.lcc.lynx.jdbc.IByIdController;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 工单管理控制实现
 * @auth lcc
 * @date 2025-03-21
 */
@RestController
@AllArgsConstructor
@RequestMapping("/bk/work/bill")
public class BkWorkBillController implements IByIdController<BkWorkBillDV> {

    private BkWorkBillService service;
    

    @Override
    public BkWorkBillService getService() {
       return service;
    }

    @RequestMapping("/uploadPicture")
    @Anonymous
    public ImgResultVO uploadPicture(@RequestParam("file") MultipartFile file) throws IOException {
        UUID uuid = UUID.randomUUID();
        String userHeaderImgUrl = "http://121.199.69.177/static/workBill/picture/";
        String filename = file.getOriginalFilename();
        int i = filename.lastIndexOf(".");
        if(i < 0){
            return ImgResultVO.error("文件名不合法");
        }
        List<String> suffixes = Arrays.asList(".png", ".jpg");
        String suffix = filename.substring(i);
        if(!suffixes.contains(suffix)){
            return ImgResultVO.error("文件格式不合法,只允许png和jpg");
        }
        String fileName = uuid.toString().replace("-", "") + filename.substring(i);

        // 如果是linux 系统
        if(System.getProperty("os.name").toLowerCase().contains("linux")){
//            直接保存文件
            file.transferTo(new File("/www/wwwroot/static/workBill/picture/" + fileName));
            return ImgResultVO.success(userHeaderImgUrl + fileName);
        }

        File localFile = null;
        try{
            // 保存上传的文件到本地
            localFile = new File(FTPUtil.LOCAL_DIRECTORY);
            if(!localFile.exists()){
                localFile.mkdirs();
            }
            localFile = new File(localFile , fileName);
            file.transferTo(localFile);
            // 使用FTP工具类上传文件到远程服务器
            if(FTPUtil.uploadFile(localFile.getPath(), "/workBill/picture")){
                return ImgResultVO.success(userHeaderImgUrl + fileName);
            }
        }catch (Exception e){
            System.out.println("上传失败" + e.getMessage());
        }finally {
            if(localFile != null){
                // 删除本地文件
                localFile.delete();
            }
        }

        return ImgResultVO.error("上传失败");
    }

}